import { cancelFirstReview, getReviewAnnotationListAsync } from 'actions/annotation-actions';
import { Tag, Row, Col, Button, message } from 'antd';
import ObjectState from 'cvat-core/src/object-state';
import { useDispatch, useSelector } from 'react-redux';
import { CombinedState } from 'reducers';
import LabelSelector from 'components/label-selector/label-selector';
import { DeleteIcon } from 'icons';
import Icon from '@ant-design/icons';
import { useState } from 'react';
import { cloneDeep } from 'lodash';
import { saveReviewLabel } from 'apis/annotation/task';
import { Label } from 'cvat-core-wrapper';
import { useParams } from 'react-router-dom-v5-compat';
import { JobStatusEnum } from 'typings/annotion/task';
import ItemAttribute from '../../object-item-attribute';

interface Props {
    origin: ObjectState;
    reviewData: ObjectState;
    clientID: number | null;
}

// 检查标签和属性是否有变化
export const isChanged = (origin: ObjectState, reviewData: ObjectState): boolean => {
    const originAttr = origin.attributes;
    const reviewAttr = reviewData.attributes;
    const originLabel = origin.label.id;
    const reviewLabel = reviewData.label.id;
    if (originLabel !== reviewLabel) {
        return true;
    }
    if (Object.keys(originAttr).length !== Object.keys(reviewAttr).length) {
        return true;
    }
    return Object.keys(originAttr).some(
        (attrID) => originAttr[attrID as unknown as any] !== reviewAttr[attrID as unknown as any],
    );
};
export default function FirstReviewEdit(props: Props): JSX.Element {
    const { origin, reviewData, clientID } = props;
    const dispatch = useDispatch();
    const params = useParams();

    const jobAttributes = useSelector((state: CombinedState) => state.annotation.job.attributes);
    const labels = useSelector((state: CombinedState) => state.annotation.job.labels);
    const attributes = jobAttributes[origin.label.id!];
    const annotationData = useSelector((state: CombinedState) => state.annotation.approval.annotationData);
    const firstReview = useSelector((state: CombinedState) => state.annotation.firstReview);
    const [newData, setNewData] = useState(cloneDeep(reviewData));

    const handleCancel = () => {
        dispatch(cancelFirstReview());
    };

    const changeAttribute = (attrID: number, value: string) => {
        setNewData({
            ...newData,
            attributes: {
                ...newData.attributes,
                [attrID]: value,
            },
        } as ObjectState);
    };

    // 切换label
    const changeLabel = (value: Label) => {
        setNewData({
            ...newData,
            label: value,
        } as ObjectState);
    };

    const handleDel = async () => {
        const data = Object.keys(annotationData).map((key) => {
            if (key == clientID) {
                return {
                    ...newData,
                    approvalStatus: 0,
                };
            }
            return annotationData[key][1];
        });
        try {
            await saveReviewLabel({
                id: firstReview.annotationId,
                subTaskId: params.sid!,
                cvatTaskId: +params.tid!,
                jobId: +params.jid!,
                annotion: JSON.stringify(data),
                auditStatus: JobStatusEnum.WAITING_FIRST_REVIEW,
            });
            dispatch(cancelFirstReview());
            dispatch(getReviewAnnotationListAsync(+params.jid!, params.sid!));
            message.success('删除成功');
        } catch (error) {
            console.log(error);
        }
    };

    /**
     * 切换属性
     * approvalStatus 1 初审修改，复审待核 2 初审修改，复审已核
     */
    const handleSubmit = async () => {
        console.log('handleSubmit', newData);
        if (!isChanged(origin, newData)) {
            message.error('前标注项与标注员填写一致，请修改标注项');
            return;
        }
        const data = Object.keys(annotationData).map((key) => {
            if (key == clientID) {
                return {
                    ...newData,
                    approvalStatus: 1,
                };
            }
            return annotationData[key][1];
        });
        try {
            await saveReviewLabel({
                id: firstReview.annotationId,
                subTaskId: params.sid!,
                cvatTaskId: +params.tid!,
                jobId: +params.jid!,
                annotion: JSON.stringify(data),
                auditStatus: JobStatusEnum.WAITING_FIRST_REVIEW,
            });
            dispatch(cancelFirstReview());
            dispatch(getReviewAnnotationListAsync(+params.jid!, params.sid!));
            message.success('修改成功');
        } catch (error) {
            console.log(error);
        }
    };
    return (
        <div className='bg-white p-3 rounded-md' style={{ border: '1px solid #E9EAED' }}>
            <div>
                <div className='font-bold text-base mb-3 font-bold'>标注员</div>
                <div>
                    <Tag color={origin.color}>{clientID}</Tag>
                    <span className='text-base'>{origin.label?.name}</span>
                </div>
                <div className='!bg-[#F7F8FA] p-3 mt-3 rounded space-y-3'>
                    {attributes.map(
                        (attribute: any): JSX.Element => (
                            <Row
                                key={attribute.id}
                                align='middle'
                                justify='start'
                                className='cvat-object-item-attribute-wrapper '
                                gutter={[16, 0]}
                            >
                                <Col span={24}>
                                    <span className='text-[#86909C]'>{attribute.name}：</span>
                                    {origin.attributes[attribute.id]}
                                </Col>
                            </Row>
                        ),
                    )}
                </div>
            </div>
            <div className='mt-18px'>
                <div className='flex justify-between items-center mb-2'>
                    <div className='font-bold text-base mb-3 font-bold'>初审员</div>
                    <Icon component={DeleteIcon} onClick={handleDel} />
                </div>
                <div className='flex items-center gap-2'>
                    <Tag color={newData.color}>{clientID}</Tag>
                    <LabelSelector
                        disabled={false}
                        labels={labels}
                        value={newData.label.id}
                        onChange={changeLabel}
                        className='cvat-objects-sidebar-state-item-label-selector w-full'
                    />
                </div>
                <div className='!bg-[#F7F8FA] p-3 mt-3 rounded space-y-3'>
                    {jobAttributes[newData.label.id!].map(
                        (attribute: any): JSX.Element => (
                            <Row
                                key={attribute.id}
                                align='middle'
                                justify='start'
                                className='cvat-object-item-attribute-wrapper '
                                gutter={[16, 0]}
                            >
                                <ItemAttribute
                                    readonly={false}
                                    attrValue={newData.attributes[attribute.id]}
                                    attrInputType={attribute.inputType}
                                    attrName={attribute.name}
                                    attrID={attribute.id}
                                    attrValues={attribute.values}
                                    changeAttribute={changeAttribute}
                                />
                            </Row>
                        ),
                    )}
                </div>
                <div className='mt-3 px-3 pb-3 flex justify-end gap-3'>
                    <Button type='primary' ghost onClick={handleCancel}>
                        取消
                    </Button>
                    <Button type='primary' onClick={handleSubmit}>
                        完成
                    </Button>
                </div>
            </div>
        </div>
    );
}
